package org.basis.enhance.concurrent.queue;

import org.basis.enhance.concurrent.executor.ThreadPriorityThreadPoolExecutor;
import org.springframework.lang.NonNull;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 任务队列，覆写了{@link TaskQueue#force(java.lang.Runnable, long, java.util.concurrent.TimeUnit)}
 * 和{@link TaskQueue#offer(java.lang.Runnable)} 方法
 * </p>
 *
 * @author wenpan 2022/12/31 11:37 上午
 */
public class TaskQueue extends LinkedBlockingQueue<Runnable> {

    private static final long serialVersionUID = 1L;

    private transient volatile ThreadPriorityThreadPoolExecutor executor = null;

    public void setExecutor(ThreadPriorityThreadPoolExecutor executor) {
        this.executor = executor;
    }

    public boolean force(Runnable runnable) {
        if (executor == null || executor.isShutdown()) {
            throw new RejectedExecutionException("Executor is shutdown.");
        }
        // forces the item onto the queue, to be used if the task is rejected
        return super.offer(runnable);
    }

    public boolean force(Runnable o, long timeout, TimeUnit unit) throws InterruptedException {
        if (executor == null || executor.isShutdown()) {
            throw new RejectedExecutionException("Executor is shutdown.");
        }
        // forces the item onto the queue, to be used if the task is rejected
        return super.offer(o, timeout, unit);
    }

    @Override
    public boolean offer(@NonNull Runnable runnable) {
        if (executor == null) {
            throw new RejectedExecutionException("The task queue does not have executor.");
        }
        //we are maxed out on threads, simply queue the object
        if (executor.getPoolSize() == executor.getMaximumPoolSize()) {
            return super.offer(runnable);
        }
        //we have idle threads, just add it to the queue
        if (executor.getSubmittedCount() <= (executor.getPoolSize())) {
            return super.offer(runnable);
        }
        //if we have less threads than maximum force creation of a new thread
        if (executor.getPoolSize() < executor.getMaximumPoolSize()) {
            return false;
        }
        //if we reached here, we need to add it to the queue, currentPoolThreadSize > max
        return super.offer(runnable);
    }

}
